import datetime
import re
import toml
import pandas

fee_info = toml.load("data/coin2/order/fee_info.toml")


def to_list(x):
  if isinstance(x, list):
    return x
  return [x]


def to_date(x):
  return pandas.DatetimeIndex([x])[0]


def get_matching_dict(dicts, me, product_name, as_of_date=None, owner=None):
  as_of_date = as_of_date if as_of_date is not None else datetime.datetime.now()
  chosen = dicts.get(me, [])
  ret = {}
  for item in to_list(chosen):
    if 'regex' in item:
      itemregex = '.*' + item['regex']
      if re.match(itemregex, product_name) is not None:
        ret.update(item)
        break
    if 'account_regex' in item and owner is not None:
      if re.match(item['account_regex'], owner) is not None:
        ret.update(item)
        break
    ret.update(item)
  ret.pop('regex', None)
  ret.pop('account_regex', None)
  return ret


def relative_norm(self):
  return (
      self.subscription_symbol
      if hasattr(self, 'subscription_symbol')
      else self.symbol)


def market_type(product):
  if product.product_type == 'Futures':
    return 'Futures'
  else:
    return 'Spot'


def get_fee_rate(market_type, exchange, product=None, owner=None):
  fee_info_product = get_matching_dict(
      dicts=fee_info,
      me=f"{market_type}.{exchange}",
      product_name=product.relative_norm,
      owner=owner)
  return (
      fee_info_product['maker_fee'],
      fee_info_product['taker_fee']
  )


def get_fee_rate_product(product):
  return get_fee_rate(market_type(product), product.exchange, product)


def get_pnl_fee(*, maker_pq, taker_pq, market_type, exchange):
  maker_fee_rate, taker_fee_rate = get_fee_rate(market_type, exchange)
  return maker_pq * maker_fee_rate + taker_pq * taker_fee_rate
